package com.zkc.zblog.redis;


import com.alibaba.fastjson.JSON;
import com.zkc.zblog.entity.ZblogUser;
import com.zkc.zblog.md5.DigestUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.zkc.zblog.redis.Constants.RedisExpire.*;

@Service("token")
public class Tokenimpl implements Token {


    @Resource
    private RedisUtils redisUtils;

    //邮箱登录验证码生成key
    @Override
    public String stringtoken(String code) {
        StringBuffer sb=new StringBuffer("code:");
        sb.append(DigestUtil.hmacSign(code)).append("-");
        sb.append(Constants.RedisKeyPrefix.ACTIVATION_MOBILE_PREFIX).append("-");
        String createTime=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        sb.append(createTime);
        return sb.toString();
    }

    /**
     *邮箱登录验证将key 和值存入redis中
     *
     * */

    @Override
    public void savecode(String token, String code) {
        redisUtils.set(token, SESSION_TIMEOUTS, code);
    }



    /**
     * 录验证码生成key 和值存入redis中
     * */
    @Override
    public void logocode(String token, String code) {
        redisUtils.set(token, DEFAULT_EXPIRE, code);
    }

    /**
     * 生成token
     *
     * @param zblogUser 用户信息
     * @return
     */
    @Override
    public String generateToken(ZblogUser zblogUser) {
        StringBuffer sb=new StringBuffer("token:");
        String uname= DigestUtil.hmacSign(zblogUser.getUname());
        sb.append(uname).append("-");
        String ucode= DigestUtil.hmacSign(zblogUser.getUcode());
        sb.append(ucode).append("-");
        String upassword= DigestUtil.hmacSign(zblogUser.getUpassword());
        sb.append(upassword).append("-");
        String createTime=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        sb.append(createTime);
        return sb.toString();
    }




    /**
     * 保存token
     *
     * @param token      token令牌
     * @param zblogUser 用户信息
     */
    @Override
    public void saveToken(String token, ZblogUser zblogUser) {
            redisUtils.set(token, SESSION_TIMEOUT, JSON.toJSONString(zblogUser));//JSON.toJSONString则是将对象转化为Json字符串
    }













}
